;
(function(_$) {
    
    const question = {
        init: function(selector, parentForm, dt) {
            const qus = {
                _selectorContainer: selector,
                _selectorContent: undefined,
                _selectorTextAnalysis: undefined,
                _ueContent: null,
                _ueTextAnalysis: null,
                _ueOption: [],
                _parentForm: parentForm,
                destroy: function() {
                    this._ueContent.destroy();
                    this._ueTextAnalysis.destroy();
                    this._ueContent = this._ueTextAnalysis = null;
                    _$(`#${this._selectorContent}`).remove();
                    _$(`#${this._selectorTextAnalysis}`).remove();
                    
                    this._ueOption.forEach((item) => {
                        item.ue.destroy();
                        _$(`#${item.selector}`).remove();
                    });
                    this._ueOption.splice(0, this._ueOption.length);
                    this._ueOption = null;
                    _$(this._selectorContainer).empty();
                },
                getQuestion: function() {
                    const answers = _$(`${this._selectorContainer} input[name="question-single-option"]:checked`).val();
                    const options = this._ueOption.map((item) => {
                        const ops = {
                            label: item.label,
                            content: item.ue.getContent(),
                        }
                        if (item.id) {
                            ops.id = item.id;
                        }
                        return ops;
                    });
                    return {
                        content: this._ueContent.getContent(),
                        answer: answers,
                        option: options,
                        text_analysis: this._ueTextAnalysis.getContent(),
                        remark: _$(`${this._selectorContainer} #remark`).val(),
                    }
                },
                reset: function() {
                    this._ueContent.setContent("");
                    this._ueTextAnalysis.setContent("");
                    this._ueOption.forEach((item) => {
                        item.ue.setContent("");
                    });
					_$(`${this._selectorContainer} #remark`).val("");
                    _$(`${this._selectorContainer} input[name="question-single-option"]`).attr("checked", false);
                },
            };
            _$(selector).empty().append(getHtml(qus, dt));
            bindListener(qus);
            initUE(qus);
			initData(qus, dt);
            return qus;
        },
    };
    
    function getHtml(qus, dt) {
		const d = new Date();
        qus._selectorContent = `question-content-${d.getTime()}`;
        qus._selectorTextAnalysis = `question-text-analysis-${d.getTime()}`;
        if (dt && dt.content && dt.content.option.length > 0) {
			dt.content.option.forEach((item) => {
                const id = item.id;
                const label = item.label;
                const content = item.content;
				const selector = `question-option-single-${d.getTime()}-${label.toLowerCase()}`;
				qus._ueOption.push({ id, selector, label, content });
			});
		} else {
			const selectorA = `question-option-single-${d.getTime()}-a`;
			const selectorB = `question-option-single-${d.getTime()}-b`;
			const selectorC = `question-option-single-${d.getTime()}-c`;
			const selectorD = `question-option-single-${d.getTime()}-d`;
			qus._ueOption.push({ selector: selectorA, label: 'A' }, 
                { selector: selectorB, label: 'B' },
                { selector: selectorC, label: 'C' },
                { selector: selectorD, label: 'D' });	
		}
        const htmlStr = `<div class="form-group">
            <label for="analysis" class="col-sm-2 control-label">题干</label>
            <div class="col-sm-10">
                <script type="text/plain" id="${qus._selectorContent}"></script>
            </div>
        </div>
        <div class="form-group">
            <label for="analysis" class="col-sm-2 control-label">答案</label>
            <div class="col-sm-10">
                <button type="button" class="btn btn-primary btn-sm btn-add-answer">添加</button>
                <button type="button" class="btn btn-primary btn-sm btn-remove-answer">删除</button>
                <ul class="option-list">
					${
						qus._ueOption.map((item, index) => {
							return `<li class="option-item">
								<label class="radio-inline" style="margin-right: 10px;">
									<input type="radio" name="question-single-option" value="${item.label || String.fromCodePoint(65 + index)}">${item.label || String.fromCodePoint(65 + index)}
								</label>
								<div class="option-content-container">
									<script type="text/plain" id="${item.selector}"></script>
								</div>
							</li>`
						}).join('')
					}
                </ul>
            </div>
        </div>
        <div class="form-group">
            <label for="analysis" class="col-sm-2 control-label">解析</label>
            <div class="col-sm-10">
                <script type="text/plain" id="${qus._selectorTextAnalysis}"></script>
            </div>
        </div>
        <div class="form-group">
            <label for="remark" class="col-sm-2 control-label">备注</label>
            <div class="col-sm-10">
                <textarea class="form-control" name="remark" id="remark"></textarea>
            </div>
        </div>`;
        return htmlStr;
    }
    
    function bindListener(qus) {
        _$(`${qus._selectorContainer} .btn-add-answer`).click(function () {
            const l = _$(`${qus._selectorContainer} .option-item`).length;
            const v = String.fromCodePoint(65 + l);    
            const d = new Date();
            const selectorX = `question-option-single-${d.getTime()}-${String.fromCodePoint(97 + l)}`;
            _$(`${qus._selectorContainer} .option-list`).append(`
                <li class="option-item">
                    <label class="radio-inline" style="margin-right: 10px;">
                        <input type="radio" name="question-single-option" value="${v}">${v}
                    </label>
                    <div class="option-content-container">
                        <script type="text/plain" id="${selectorX}"></script>
                    </div>
                </li>`
            );

            qus._ueOption.push({
                selector: selectorX,
                ue: window.UE.getEditor(selectorX, {
                    autoHeight: false
                }),
            });
        });
    
        _$(`${qus._selectorContainer} .btn-remove-answer`).click(function () {
            _$(`${qus._selectorContainer} .option-item:last-child`).remove();
            const item = qus._ueOption.pop();
            item && item.ue.destroy();
        });
    }
    
    function initUE(qus) {
        console.warn(qus._selectorContent);
        console.warn(qus._selectorTextAnalysis);
        qus._ueContent = window.UE.getEditor(qus._selectorContent, {
            autoHeight: false
        });
        qus._ueTextAnalysis = window.UE.getEditor(qus._selectorTextAnalysis, {
            autoHeight: false
        });
        qus._ueOption.forEach((item) => {
            item.ue = window.UE.getEditor(item.selector, {
                autoHeight: false
            });
        });
        console.warn(qus._ueContent);
    }

	function initData(qus, dt) {
        console.warn(qus, dt);
        if (!dt) {
            return;
        }
        qus._ueContent.ready(function() {
            qus._ueContent.setContent(dt.content.content);
        });  
        qus._ueTextAnalysis.ready(function() {
            qus._ueTextAnalysis.setContent(dt.content.text_analysis);
        });
        _$(`${qus._selectorContainer} #remark`).val(dt.content.remark);
        qus._ueOption.forEach((item) => {
            item.ue.ready(function() {
                item.content && item.ue.setContent(item.content);
            });
        });
        if (dt.content && dt.content.answer) {
            _$(`${qus._selectorContainer} input[value="${dt.content.answer}"]`).attr("checked", true);
        }
    }
	
    _$.fn.extend({
        questionSingle: question,
    });
})($);